package controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import models.Image;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Http.MultipartFormData;
import play.mvc.Http.MultipartFormData.FilePart;
import play.mvc.Result;
import views.html.imageloader.imageupload;

/*
 * ImageLoader controller.
 * Used to store and render the images.
 * Author: Khalmuratov Alisher.
 */

public class ImageLoader extends Controller {

	public static Result index()
	{
		return ok(imageupload.render(Form.form(ImageForm.class)));
	}
	
	public static Result add()
	{
		MultipartFormData body = request().body().asMultipartFormData();
		FilePart fp = body.getFile("image");
		if(fp!=null)
		{
			String filename = fp.getFilename();
			String type = fp.getContentType();
			File file = fp.getFile();
			byte[] barray = new byte[(int)file.length()];
			try{
				FileInputStream fis = new FileInputStream(file);
				fis.read(barray);
				fis.close();
			}catch(Exception e){}
			System.out.println("here");
			Image.create(barray, filename, type).save();
			flash("success", "Image is succesfully uploaded.");
			return redirect(routes.ImageLoader.index());
		}
		else
		{
			return redirect(routes.ImageLoader.index());
		}
	}
	
	public static Result image(Long id)
	{
		Image img = Image.find.byId(id);
		response().setContentType(img.type);
		return ok(img.image).as(img.type);
	}
	
	public static Result thumb(Long id)
	{
		Image img = Image.find.byId(id);
		response().setContentType(img.type);
		return ok(img.thumb).as(img.type);
	}
	
	public static Result refresh(Long id, String op)
	{
		return ok();
	}
	
	public static class ImageForm
	{
		public File image;
	}
}
